﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RedditWallpaperLib;

namespace RedditWallpaperTrayApp
{
    public partial class Form1 : Form
    {
        private NotifyIcon trayIcon;
        private ContextMenu trayMenu;
        private Timer timer;
        
        public Form1()
        {
            InitializeComponent();

            trayMenu = new ContextMenu();
            trayMenu.MenuItems.Add("Exit", OnExit);
            trayMenu.MenuItems.Add("Sync Wallpaper", OnSyncWallpaper);

            trayIcon = new NotifyIcon();
            trayIcon.Text = "Reddit Wallpaper";
            Bitmap bmp = RedditWallpaperTrayApp.Properties.Resources.redditAlien;
            trayIcon.Icon = Icon.FromHandle(bmp.GetHicon());

            trayIcon.ContextMenu = trayMenu;
            trayIcon.Visible = true;

            timer = new Timer();
            timer.Interval = (int) TimeSpan.FromHours(1).TotalMilliseconds;
            timer.Tick += new EventHandler(timer_Tick);            

            ChangeWallpaper();

            timer.Start();
        }       

        protected override void OnLoad(EventArgs e)
        {
            Visible = false;
            ShowInTaskbar = false;

            base.OnLoad(e);
        }

        private void OnExit(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void OnSyncWallpaper(object sender, EventArgs e)
        {
            ChangeWallpaper();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            timer.Stop();
            ChangeWallpaper();
            timer.Start();
        }

        private void ChangeWallpaper()
        {
            try
            {
                RedditWallpaper redditWallpaper = new RedditWallpaper();
                redditWallpaper.ChangeWallpaper();
                trayIcon.Text = "updated: " + DateTime.Now;
            }
            catch (Exception)
            {
                trayIcon.Text = "failed: " + DateTime.Now;
            }
        }
    }
}
